<?php
/**
 * Pert Library
 * Session Array Class
 *
 * @author	Emre Hasegeli <hasegeli@gmail.com>
 * @license	GNU General Public License v3
 */

namespace Pert;

class SessionArray implements \ArrayAccess,
		\IteratorAggregate,
		\Countable
{
	private $name;

	private $offsetArray = array();

	public function __Construct($name)
	{
		$this->name = $name;

		if(isset($_SESSION[$this->name]))
			foreach(unserialize($_SESSION[$this->name]) AS $element => $value)
				$this->OffsetSet($element,
						$value);
	}

	public function __destruct()
	{
		if(isset($this->offsetArray))
			$_SESSION[$this->name] = serialize($this->offsetArray);
	}

	public function __ToString()
	{
		return $this->name;
	}

	public function OffsetExists($offset)
	{
		return isset($this->offsetArray[$offset]);
	}

	public function OffsetGet($offset)
	{
		if($this->__Isset($offset))
			return $this->offsetArray[$offset];
	}

	public function OffsetSet($offset,
			$value)
	{
		$this->offsetArray[$offset] = $value;
	}

	public function OffsetUnset($offset)
	{
		unset($this->offsetArray[$offset]);
	}

	public function GetIterator()
	{
		return new Iterator($this->offsetArray);
	}

	public function Count()
	{
		return count($this->offsetArray);
	}

	public function Delete()
	{
		unset($this->offsetArray);

		unset($_SESSION[$this->name]);
	}

	public static function Select($name)
	{
		if(isset($_SESSION[$name]))
			return new self($name);
	}
}
